#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

// 执行
int intervals = 1000;

// 计算pi
void* calculate_pi(void* arg) {
	
	unsigned int seed = time(NULL);
	int circle_points = 0;
	int square_points = 0;
	
	// 将参数 void* 强转为 int* 类型，然后从指针中取出值
	int interval = *((int*) arg);
	
	for (int i = 0; i < interval * interval; i++) {
		double rand_x = (double)rand_r(&seed) / RAND_MAX;
		double rand_y = (double)rand_r(&seed) / RAND_MAX;
		
		if (rand_x * rand_x + rand_y * rand_y <= 1) {
			circle_points++;
		}
		square_points++;
	}
	
	double pi = (double) (4 * circle_points) / square_points;
	
	printf("The estimated PI is: %1f in %d times\n", pi, interval * interval);
	
	// 线程正常结束
	pthread_exit(0);
}

int main () {

	clock_t start, delta;
	double time_used;
	
	start = clock();
	
	pthread_t calculate_threads[10];
	// 参数数组，线程函数的参数是一个指针
	int args[10];
	
	
	for (int i = 0; i < 10; i++) {
		// 循环十次，创建十个线程
		args[i] = intervals * (i+1);
		// 数组的引用为该数组的首地址，args + 1 表示首地址向后偏移一个数据长度的地址
		pthread_create(calculate_threads + i, NULL, calculate_pi, args + i);
	}
	
	for (int i = 0; i < 10; i++) {
		// 等待十个子线程结束
		pthread_join(calculate_threads[i], NULL);
	}
	
	delta = clock() - start;
	printf("The time token in total: %1f seconds\n", (double) delta / CLOCKS_PER_SEC);
	
	return 0;
}

